<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalStorage</title>

    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <div class="wrapper">
        <p></p>
        <h2>LOCAL TAPAS</h2>
        <ul class="plates">
            <li>Loading Tapas</li>
        </ul>
        <form action="" class="add-items">
            <input type="text" name="item" autofocus placeholder="Item Name" required>
            <input type="submit" value="+Add Item">
        </form>
    </div>

    <script>
        // 1. form +ul
        // 2. lodaing...
        // 3. 前端数据持久化 前端有数据库 5M 
        // const let 与var 不同 不会变量提升 会进入暂时性死区
        // 变量提升其实不好
        const addItems=document.querySelector('.add-items');
        const itemList=document.querySelector('.plates');
        const items=JSON.parse(
                localStorage.getItem("items")
            )||[];
        // 负责将todos 显示到列表
        function populateList(plates=[],platesList){// plates=[] 设置参数默认值 
            // data-index数据属性 可以通过dataset拿到
            platesList.innerHTML=plates.map((plate,i)=>`
                <li>
                    <input type="checkbox" data-index=${i} id="item${i}" 
                    ${plate.done? 'checked':''}>
                    <label for="item${i}">${plate.text}</label>
                </li>
            `).join('');
        }
        function addItem(event){
            event.preventDefault();
            const text =this.querySelector('[name=item]').value;
            // console.log(text);
            const item={
                text,//es6 
                done:false
            }
            items.push(item);
            populateList(items,itemList);
            // storage
            
            console.log(JSON.stringify(items));
            localStorage.setItem('items',JSON.stringify(items));
            this.reset();
        }
        // function init(){
        //     // 取出loaclstorage
        //     // [].lenth >0
        //     // populateList
        //     const storageItems=JSON.parse(
        //         localStorage.getItem("items")
        //     );
        //     if(storageItems.length){
        //         populateList(storageItems,itemList);
        //     }
        // }
        addItems.addEventListener('submit',addItem);
        // init();
        populateList(items,itemList);
    </script>
</body>
</html>